﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;
using System.Linq;
using System.Reflection;

namespace RGB.SharePoint.SPBlockFileTypes
{
    public partial class BlockFileTypesControl : UserControl
    {
        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SetDocumentLibraryList();
                ResetValues();
            }
            SPWeb web = SPContext.Current.Web;
            SPUser currentUser = web.CurrentUser;
            if (!web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
            {
                SubmitButton.Enabled = false;
                RemoveBlockingButton.Enabled = false;
                MessageLabel.Text = "Sorry, you don't have sufficient permissions for this operation.";
            }
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(DocumentLibraryList.SelectedValue))
                {
                    SPWeb web = SPContext.Current.Web;
                    SPList list = web.Lists[new Guid(DocumentLibraryList.SelectedValue)];
                    list.RootFolder.Properties[Constants.EXTENSIONS_LIST_PROPERTY] = FileExtensionsTextBox.Text.Trim();
                    list.RootFolder.Properties[Constants.BLOCK_TYPE_PROPERTY] = Options.SelectedValue.Trim();
                    list.RootFolder.Update();
                    if (list.EventReceivers.OfType<SPEventReceiverDefinition>().SingleOrDefault(ev => ev.Class.Equals(typeof(BlockFileTypesEventReceiver).FullName)) == null)
                    {
                        list.EventReceivers.Add(SPEventReceiverType.ItemAdding, Assembly.GetExecutingAssembly().FullName, typeof(BlockFileTypesEventReceiver).FullName);
                    }
                }
                MessageLabel.Text = "Settings saved successfully.";
            }
            catch (Exception ex)
            {
                MessageLabel.Text = ex.Message;
            }
        }

        protected void DocumentLibraryList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ResetValues();
        }

        protected void RemoveBlockingButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(DocumentLibraryList.SelectedValue))
                {
                    SPWeb web = SPContext.Current.Web;
                    SPList list = web.Lists[new Guid(DocumentLibraryList.SelectedValue)];
                    list.RootFolder.Properties[Constants.EXTENSIONS_LIST_PROPERTY] = null;
                    list.RootFolder.Properties[Constants.BLOCK_TYPE_PROPERTY] = null;
                    list.RootFolder.Update();
                    var eventReceiver = list.EventReceivers.OfType<SPEventReceiverDefinition>().SingleOrDefault(ev => ev.Class.Equals(typeof(BlockFileTypesEventReceiver).FullName));
                    if (eventReceiver != null)
                    {
                        eventReceiver.Delete();
                    }
                    ResetValues();
                    MessageLabel.Text = "Block settings removed successfully from " + list.Title;
                }
            }
            catch (Exception ex)
            {
                MessageLabel.Text = ex.Message;
            }            
        }

        #endregion

        #region Private Methods

        private void ResetValues()
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                SPList list = web.Lists[new Guid(DocumentLibraryList.SelectedValue)];
                if (list.RootFolder.Properties.ContainsKey(Constants.EXTENSIONS_LIST_PROPERTY))
                {
                    FileExtensionsTextBox.Text = list.RootFolder.Properties[Constants.EXTENSIONS_LIST_PROPERTY].ToString();
                }
                if (list.RootFolder.Properties.ContainsKey(Constants.BLOCK_TYPE_PROPERTY))
                {
                    if (list.RootFolder.Properties[Constants.BLOCK_TYPE_PROPERTY].ToString().ToLower().Equals(BlockType.Allow.ToString()))
                    {
                        Options.SelectedIndex = 0;
                    }
                    else
                    {
                        Options.SelectedIndex = 1;
                    }
                    FileExtensionsTextBox.Text = list.RootFolder.Properties[Constants.EXTENSIONS_LIST_PROPERTY].ToString();
                }
                else
                {
                    Options.SelectedIndex = 0;
                    FileExtensionsTextBox.Text = string.Empty;
                }
            }
            catch (Exception ex)
            {
                MessageLabel.Text = ex.Message;                
            }            
        }

        private void SetDocumentLibraryList()
        {
            try
            {
                DataTable dt = new DataTable();
                DataColumn docLibraryTitleColumn = new DataColumn(Constants.TITLE_COLUMN, typeof(string));
                DataColumn docLibraryIdColumn = new DataColumn(Constants.ID_COLUMN, typeof(string));
                dt.Columns.Add(docLibraryTitleColumn);
                dt.Columns.Add(docLibraryIdColumn);
                SPWeb web = SPContext.Current.Web;
                foreach (SPList list in web.Lists.OfType<SPDocumentLibrary>())
                {
                    dt.Rows.Add(list.Title, list.ID);
                }
                DocumentLibraryList.DataSource = dt;
                DocumentLibraryList.DataTextField = Constants.TITLE_COLUMN;
                DocumentLibraryList.DataValueField = Constants.ID_COLUMN;
                DocumentLibraryList.DataBind();
            }
            catch (Exception ex)
            {
                MessageLabel.Text = ex.Message;
            }
        }

        #endregion
    }
}
